/**
 *
 */
require(['../config'], function () { require(["PageCommon1"]); });

(function (factory) {
    define("PageCommon1", [
        'jquery',
        'Vue',
        'UUID',
        'underscore',
        'layui',
        'VeeValidate',
        'VeeMessages',
        'bootstrap'
    ], factory);
})(function ($, Vue, UUID, _, layui, VeeValidate, VeeMessages, bootstrap) {

    const isMobile = {
        messages: {
            zh_CN: (field, args) => field + " 必须是11位手机号码",
        },
        validate: (value, args) => {
            return value.length === 11 && /^((13|14|15|17|18)[0-9]{1}\d{8})$/.test(value);
        }
    }
    const isUnique = {
        getMessage(field, params, data) {
            return (data && data.message) || field + " 不能存在同样的记录.";
        },
        validate: (value, args) => {
            // console.log(PageObj.contextPath + "/data/" +args[0] + "=" + value);
            var r = new Promise(resolve => {
                $.get(PageObj.contextPath + "/data/" +args[0] + "=" + value).done(function(data){
                    resolve({
                        valid: data.data.length <= 0,
                        data: value
                    });
                });
            });
            return r;
        }
    }
    VeeValidate.Validator.extend('mobile', isMobile);
    VeeValidate.Validator.extend('unique', isUnique);

    Vue.use(VeeValidate, {
        locale: "zh_CN",
        strict: true,
        events: "blur|change",
        dictionary: {
            zh_CN: {
                messages: VeeMessages.messages,
                attributes: VeeMessages.attributes
            }
        },
    });

    const dictionary = {
        zh_CN:{
            messages: {
                email: () => '邮箱格式不正确',
                mobile: () => '手机格式应该为13,14,15,17,18开头的11位数字',
                unique: (field) => field + ' 已存在，不能有重复的值',
            }
        }
    };
    VeeValidate.Validator.localize(dictionary);

    var load = function (url) {
        $.get(url, function (data) {
            PageObj.items = data;
        });
    };

    var getValue = function (url, name, target) {
        $.get(url).done(function (data) {
            $("input[name='" + target + "']").val(data[name]);
        });
    }

    // 将表单数据转成服务器能接收的json数据,重名数组的未考虑
    var formToArray = function ($form) {
        var items = $form.serializeArray();
        var data = {};
        $.map(items, function (n, i) {
            data[n['name']] = n['value'];
        });
        return data;
    };

    // 生成下拉列表, column:PageObj.columns中有dbDropDown属性的列, 在表单的created事件及某些input的change事件中调用
    var dropDropDownList = function (column, val, jqo, selectName) {
        var sets = column.dbDropDown.split(",");
        if (sets.length >= 4) {
            var url = PageObj.contextPath + "/data/" + sets[0] + "?where-" + sets[1] + "=" + (val ? val : PageObj.columns[sets[1]].default);
            //fetch(url).then(function(res){ return res.json() }).then(function(jsonVal){
            $.get(url).done(function (res) {
                // console.log(url);
                if (res.data.length > 0) {
                    column.options = {};
                    $.map(res.data, function (d, i) {
                        column.type = "select";
                        column.options[d[sets[2]]] = d[sets[3]];
                    });
                }

                if (jqo && selectName) {
                    //移除对应select元素的options,再加上新的
                    var _select = jqo.parents("form").find("select[name='" + selectName + "']");
                    _select.empty();
                    $.each(column.options, function (o, i) {
                        _select.append("<option value='" + o + "'>" + column.options[o] + "</option>");
                    });
                }
            });
        }
    }

    var vm = new Vue({
        el: "#app",
        data: function () { return PageObj; },
        beforeCreate: function () {
            load(PageObj.dataUrl);
        },
        watch: {
            dataUrl: {
                handler: function (newValue, oldValue) { load(newValue); }
            },
            deep: true
        },
        methods: {
            search: function (val) {
                //移除原来生成的查询条件
                var newUrl = PageObj.dataUrl.replace(/([?]+)where-([^=]+)=[^&]+/g, "?").replace(/([&?]+)where-([^=]+)=[^&]+/g, "");
                if (val !== undefined && val !== null && val.replace(/(^s*)|(s*$)/g, "").length > 0) {
                    var cols = "";
                    var oper = "-like=";
                    //判断val中是否有相关的查询字段，例如：学校名称:四川
                    //查询时可以指定列名：列名和值中间用"="表示相等关系，":"表示包含关系
                    //如果输入的列名内容在多个列的标题中都包含，则将这几个列都纳入查询
                    var sc = val.match(/([^=:：]*)[=:：]+(.*)/);
                    for (column in PageObj.columns) {
                        if (PageObj.columns[column].skip && PageObj.columns[column].skip.indexOf("search") > -1) continue;
                        if (sc && sc.length > 2) {
                            if (PageObj.columns[column].title.indexOf(sc[1]) >= 0) {
                                cols += (cols.length > 0 ? "~" : "") + column;
                            }
                        } else {
                            if (PageObj.columns[column].type !== 'hidden') {
                                cols += (cols.length > 0 ? "~" : "") + column;
                            }
                        }
                    }

                    oper = val.indexOf("=") >= 0 ? "=" : "-like=";
                    val = (sc && sc.length > 2 ? sc[2] : val).replace(/[\s=:]+/g, "");

                    newUrl += (newUrl.indexOf("?") > 0 ? "&" : "?") + "where-" + cols + oper + val;
                }
                //console.log(newUrl);
                PageObj.dataUrl = newUrl;
            },
            addItem: function () {
                var _self = this;
                
                // 清除表单校验状态
                var editform_div = _self.$refs.editform_div;
                editform_div.errors.clear();

                layui.use('layer', function(){
                    var layer = layui.layer;
                    layer.open({
                        type: 1,
                        title: PageObj.title,
                        closeBtn: 1,
                        area: '600px',
                        skin: 'layui-layer-molv',
                        shadeClose: true,
                        btn: [' 提 交 ', ' 取 消 '],
                        btnAlign: 'c',
                        content: $('#maintain-form'),
                        success: function (layero, index) {
                            //表单 Reset
                            //layero.find("form").each(function(){ this.reset(); });
                            //设置默认值
                            layero.find("input,select,textarea").each(function () {
                                if (!PageObj.columns[this.name]) return false;
                                var defVal = PageObj.columns[this.name].default;
                                if (defVal && defVal !== null && defVal.replace(/(^s*)|(s*$)/g, "").length > 0) {
                                    defVal = (defVal.indexOf(")") > 0) ? eval(defVal) : defVal;
                                } else {
                                    defVal = "";
                                }
                                if (this.type === "radio") {
                                    this.checked = (this.value === defVal);
                                } else {
                                    this.value = defVal;
                                }
                            });
                        },
                        yes: function (index, layero) {
                            // 检查表单是否验证通过
                            editform_div.$validator.validateAll().then((result) => {
                                if (result) {
                                    var data = formToArray(layero.find("form"));
                                    //console.log(data);
                                    var affected = 0;
                                    if (PageObj.batch) {
                                        var batch = PageObj.batch;
                                        var records = [];
                                        $.map(batch, function (c, i) {
                                            if (data[c]) {
                                                // 批量生成，截取第一个数字及后一个数字
                                                var names = data[c].match(/([^#]*)#+(\d+)->+(\d+)#+(\S*)/);
                                                if (names !== null && names.length > 4) {
                                                    var min = Number(names[2]);
                                                    var max = Number(names[3]);
                                                    for (var i = min; i <= max; i++) {
                                                        var newData = $.extend(true, {}, data);
                                                        //前面补0
                                                        var z = "000000000" + i;
                                                        z = z.substring(z.length - names[3].length);
                                                        newData[c] = names[1] + z + names[4];
                                                        records.push(newData);
                                                    }
                                                }
                                            }
                                        });
                                        if (records.length === 0) { records.push(data); }
            
                                        var url = _self.dataUrl.replace(/[?](.*)/g, "") + "/multi";
                                        $.ajax({
                                            type: "POST",
                                            url: url,
                                            contentType: "application/json",
                                            data: JSON.stringify({ "rows": records }),
                                            success: function (data) {
                                                layer.close(index);
                                                load(PageObj.dataUrl);
                                                alert("数据增加成功!");
                                            },
                                            fail: function (data) {
                                                alert("增加失败,请检查输入的信息!");
                                            }
                                        });
                                    } else {
                                        $.ajax({
                                            type: "POST",
                                            url: _self.dataUrl.replace(/[?](.*)/g, ""),
                                            contentType: "application/json", // 一定要加，否则后台会提示找不到RequestBody
                                            data: JSON.stringify(data),
                                            success: function (data) {
                                                affected = affected + data.affectedRows;
                                                layer.close(index);
                                                load(PageObj.dataUrl);
                                                alert("数据增加成功!");
                                            }
                                        });
                                    }
                                } else {
                                    alert("请输入正确的内容.");
                                    return;
                                }
                            });
                        },
                    });
                });
            },
        }
    });

    Vue.component("data-table", {
        template: "#data-table",
        props: ["items", "columns"],
        beforeCreate: function () { load(PageObj.dataUrl); },
        methods: {
            editItem: function (url, event) {
                var _self = this;
                
                //清除表单的校验状态
                var editform_div = _self.$parent.$refs.editform_div;
                editform_div.errors.clear();

                //把当前行的背景色变为黄色
                var $selectedTr = $(event.currentTarget).parents("tr");
                var bg = $selectedTr.css("background");
                $selectedTr.css("background", "yellow");
                $.ajax({
                    type: "GET",
                    url: url,
                    success: function (bResource) {
                        //console.log(bResource);
                        layui.use('layer', function(){
                            var layer = layui.layer;
                            layer.open({
                                type: 1,
                                title: PageObj.title,
                                closeBtn: 1,
                                area: '600px',
                                skin: 'layui-layer-molv', //没有背景色
                                shadeClose: true,
                                btn: ['提 交', '取 消'],
                                btnAlign: 'c',
                                content: $('#maintain-form'),
                                success: function (layero, index) {
                                    layero.find("input,select,textarea").each(function () {
                                        if (bResource[this.name] === undefined) return false;
                                        if (this.type === 'radio') {
                                            this.checked = (bResource[this.name] === this.value);
                                        } else {
                                            this.value = bResource[this.name];
                                        }
                                    });
                                },
                                yes: function (index, layero) {
                                    //console.log(url);
                                    // 进行输入校验
                                    editform_div.$validator.validateAll().then((result) => {
                                        if (result) {
                                            var data = formToArray(layero.find("form"));
                                            $.ajax({
                                                type: "PUT",
                                                url: url,
                                                contentType: "application/json", // 一定要加，否则后台会提示找不到RequestBody
                                                data: JSON.stringify(data),
                                                success: function (data) {
                                                    layer.close(index);
                                                    load(PageObj.dataUrl);
                                                    alert("数据修改成功！");
                                                }
                                            });
                                        } else {
                                            alert("请输入正确的内容.");
                                            return;
                                        }
                                    })
                                },
                                end: function (index) {
                                    layer.close(index);
                                    $selectedTr.css("background", (bg == "" ? "white" : bg));
                                }
                            });
                        });
                    }
                });
            },
            deleteItem: function (url, event) {
                // console.log(url);
                var $selectedTr = $(event.currentTarget).parents("tr");
                var bg = $selectedTr.css("background");
                $selectedTr.css("background", "yellow");
                layui.use('layer', function(){
                    var layer = layui.layer;
                    layer.msg("请确认是否要删除所选择的记录？", {
                        time: 0,
                        btn: [" 确定 ", " 取消 "],
                        yes: function (index) {
                            $.ajax({
                                type: 'DELETE',
                                url: url,
                                success: function (data) {
                                    load(PageObj.dataUrl);
                                },
                                complete: function (xhr, ts) {
                                }
                            });
                            layer.close(index);
                        },
                        end: function () {
                            $selectedTr.css("background", (bg == "" ? "white" : bg));
                        }
                    });
                });
            },
            orderBy: function (column, event) {
                var newUrl = PageObj.dataUrl;
                if (PageObj.columns[column].skip && PageObj.columns[column].skip.indexOf("order") > -1) return;
                if (newUrl.indexOf("orderBy") > 0) {
                    if (newUrl.indexOf(column) > 0) {
                        if (newUrl.indexOf("-" + column) > 0) {
                            newUrl = newUrl.replace(/orderBy=([^&]+)/g, "orderBy=" + column);
                        } else {
                            newUrl = newUrl.replace(/orderBy=([^&]+)/g, "orderBy=-" + column);
                        }
                    } else {
                        newUrl = newUrl.replace(/orderBy=([^&]+)/g, "orderBy=" + column);
                    }
                } else {
                    newUrl += (newUrl.indexOf("?") > 0 ? "&" : "?") + "orderBy=" + column;
                }
                //console.log(newUrl);
                PageObj.dataUrl = newUrl;
            },
            orderUp: function (column) {
                return (PageObj.dataUrl.indexOf("orderBy=" + column) > 1);
            },
            orderDown: function (column) {
                return (PageObj.dataUrl.indexOf("orderBy=-" + column) > 1);
            },
        },
    });

    Vue.component("page-navigation", {
        template: "#page-navigation",
        props: ["pageinfo"],
        methods: {
            toPage: function (page, event) {
                PageObj.dataUrl = PageObj.dataUrl.replace(/page=\d+/, "page=" + page);
                $("#page").val(page);
            }
        }
    });

    Vue.component("div-additem", {
        template: "#div-additem",
        props: ["columns"],
        created: function () {
            //初始化各字段下拉列表
            $.map(PageObj.columns, function (c, i) {
                if (c.dbDropDown) { dropDropDownList(c); }
            });
        },
        mounted: function(){
            Object.keys(PageObj.columns).forEach(key => {
                var c = PageObj.columns[key];
                if (c.inputType) {
                    if (c.inputType === "datetime" || c.inputType === "date" || c.inputType === "time"){
                        layui.use('laydate', function(){
                            var laydate = layui.laydate;
                            laydate.render({
                                elem: "input[name='" + key + "']",
                                type: c.inputType
                            })
                        });
                    }
                }
            });
        },
        methods: {
            itemChanged: function (event) {
                var _this = $(event.currentTarget);
                if (_this.attr("ddList")) {
                    var ins = _this.attr("ddList").split(",");
                    //根据用户输入设置其他关联项的下拉列表
                    var val = _this.val();
                    if (!val.match(/[\{\}\[\]:]+/g)) {
                        //不能包含有{,},[,],:等特殊字符
                        $.each(ins, function (i, c) {
                            dropDropDownList(PageObj.columns[c], val, _this, c);
                        });
                    } else {
                        alert("请输入正确的内容");
                        _this.val("");
                    }
                }
                if (_this.attr("changeSets")) {
                    //根据用户输入设置其他关联项的值
                    var sets = _this.attr("changeSets").split(",");
                    if (sets.length >= 3) {
                        if (_this.attr("type") === "text") {
                            //input从后台获取数据
                            var url = PageObj.contextPath + "/data/" + sets[0] + "?where-" + sets[1] + "=" + _this.val();
                            //console.log(url);
                            $.get(url).done(function (res) {
                                _this.parents("form").find("input[name='" + sets[sets.length < 4 ? 2 : 3] + "']").each(function () {
                                    $(this).val(res.data[0] ? res.data[0][sets[2]] : "");
                                });
                            });
                        } else if (_this.find("option")) {
                            //select直接获取选中选项的文本
                            _this.parents("form").find("input[name='" + sets[sets.length < 4 ? 2 : 3] + "']").each(function () {
                                $(this).val(_this.find("option:selected").text());
                            });
                        }
                    }
                }
            },
            isPassed: function() {
                this.$validator.validateAll();
                return this.errors.any();
            }
        }
    });

});